package com.zeng.service.restmodel;

import com.alibaba.fastjson.JSONObject;
import com.zeng.bean.restmodel.RestModelInfo;
import com.zeng.bean.restmodel.RestQueryParam;
import com.zeng.bean.restmodel.RestQueryPropParam;
import com.zeng.mapper.restmodel.RestModelMapper;
import com.zeng.pojo.restmodel.BaseRestModel;
import lombok.Data;
import org.springframework.web.context.WebApplicationContext;

import java.util.List;
import java.util.stream.Stream;

/**
 * restful 模型服务类
 */
@Data
public class RestModelService {

    private Class<? extends BaseRestModel> clazz;
    private RestModelInfo modelInfo;
    private WebApplicationContext appContext;
    private RestModelMapper mapper;

    public RestModelService(RestModelInfo modelInfo, WebApplicationContext appContext) {
        this.appContext = appContext;
        this.modelInfo = modelInfo;

        this.mapper = appContext.getBean(RestModelMapper.class);
        this.clazz = modelInfo.getClazz();
    }

    public static RestModelService load(RestModelInfo modelInfo, WebApplicationContext appContext) {
        return new RestModelService(modelInfo, appContext);
    }

    /**
     * 通用查询
     */
    public List<JSONObject> select(RestQueryParam param) throws Exception {
        if(!modelInfo.isUse() || !modelInfo.isUseGet()) throw new Exception("查询接口未启用");
        if(!modelInfo.onSelect(param)) return null;

        List<JSONObject> jsonObjects = mapper.select(param);
        return jsonObjects.stream().filter(f -> modelInfo.onSelected(f)).toList();
    }


    /**
     * 通用更新
     * @return 更新后的数据
     */
    public void update(RestQueryParam param) throws Exception {
        if(!modelInfo.isUse() || !modelInfo.isUsePut()) throw new Exception("更新接口未启用");
        if(!modelInfo.onUpdate(param)) return;
        mapper.update(param);
    }

    /**
     * 通用插入
     */
    public JSONObject insert(RestQueryParam param) throws Exception {
        if(!modelInfo.isUse() || !modelInfo.isUsePost()) throw new Exception("插入接口未启用");
        if(!modelInfo.onInsert(param)) return null;

        //去除主键
        //TODO:硬编码改进
        param.setSelectParams(param.getSelectParams().stream().filter(p -> !p.getName().equalsIgnoreCase("id")).toList());

        mapper.insert(param);

        RestQueryParam selectParam = RestQueryParam.defaultSelect(clazz);
        selectParam.getWhereParams().add(new RestQueryPropParam("id",param.getId()));
        List<JSONObject> jsonObjects = select(selectParam);

        return jsonObjects.get(0);
    }

    /**
     * 通用删除
     * @param param
     * @throws Exception
     */
    public void  delete(RestQueryParam param) throws Exception {
        if(!modelInfo.isUse() || !modelInfo.isUseDelete()) throw new Exception("删除接口未启用");
        if(!modelInfo.onDelete(param)) return;
        mapper.delete(param);
    }

}
